<?php


namespace app\common\model\system;

use app\common\model\BaseModel;



/**
 * 系统用户
 * Class SysMenu
 * @package app\common\model\system
 */
class SysUser extends BaseModel
{
    protected $name = 'system_user';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /** 查询条件
    * @param object $query
    * @param array $param
    */
    public function scopeCustom(object $query, array $param)
    {
        //账户
        if ($username = $param['name'] ?? '') {
            $query->whereLike('username|nickname', '%' . trim($username) . '%');
        }
        if(!empty($param['group_id'])){
            $uids = SysUserGroup::where('group_id',$param['group_id'])->column('user_id');
            $query->whereIn('id',$uids);
        }
        if(!empty($param['role_id'])){
            $uids = SysUserRole::where('role_id',$param['role_id'])->column('user_id');
            $query->whereIn('id',$uids);

        }
        if(!empty($param['kid']) && $param['kid']>2){
            $query->where('id', $param['kid']);
        }
    }

    /**
     * 管理员显示字段
     */


    public static function showField(): array
    {
        return [
            'id', 'username', 'nickname', 'phone', 'email', 'avatar', 'signed', 'dashboard',
            'sex', 'role_id', 'group_id', 'remark', 'created_at', 'login_ip', 'status','state','is_reply'
        ];

    }
    /**
     * 角色
     */
    public function role()
    {
        return $this->hasMany(SysUserRole::class, 'user_id', 'id')->field('id,user_id,role_id');
    }
    /**
     * 多对多角色关联
     */
    public function roles()
    {
        return $this->belongsToMany(SysRole::class, SysUserRole::class,'role_id','user_id');
    }
    /**
     * 多对多分组
     */
    public function groups()
    {
        return $this->belongsToMany(SysGroup::class, SysUserGroup::class,'group_id','user_id');

    }


    /**
     * 分组
     */
    public function group()
    {
        return $this->hasMany(SysUserGroup::class, 'user_id', 'id');
    }
//    public function getGroupIdAttr($value,$data)
//    {
//
//        return $value?json_decode($value):"";
//    }
    /**
     * @notes  获取部门id集
     * @param $value
     * @param $data

     */
    public function getGroupIdAttr($value, $data)
    {
        return SysUserGroup::where('user_id', $data['id'])->column('group_id');
    }
        /**
     * @notes  获取角色id集
     * @param $value
     * @param $data

     */
    public function getRoleIdAttr($value, $data)
    {
        return SysUserRole::where('user_id', $data['id'])->column('role_id');
    }

}